# 京东商品信息爬虫，通过selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time
import random
def getGood(driver):
    try:
        num = random.randint(2000,6000) 
        js_code='window.scrollTo(0,'+str(num)+')'
        driver.execute_script(js_code)
        time.sleep(random.randint(2,5))
        good_list = driver.find_elements(By.CLASS_NAME,'gl-item')
        n=1
        for good in good_list:
            good_url=good.find_elements(By.CSS_SELECTOR,'.p-img a')[0].get_attribute('href')
            good_name=good.find_elements(By.CSS_SELECTOR,'.p-name em')[0].text
            good_price=good.find_elements(By.CSS_SELECTOR,'.p-price')[0].text
            good_commit=good.find_elements(By.CSS_SELECTOR,'.p-commit')[0].text
            good_content=f'''链接:{good_url}名称:{good_name}，价格:{good_price}，评价:{good_commit}\n'''
            print(good_content)
            with open('jd.txt','a') as fp:
                fp.write(good_content)

        next_tag = driver.find_element(By.CLASS_NAME,'pn-next')
        next_tag.click()
        time.sleep(2)
        getGood(driver)
        time.sleep(15)
    finally:
        driver.close()

if __name__=='__main__':
    good_name=input("输入商品名：").strip()
    driver=webdriver.Chrome()
    driver.implicitly_wait(10)
    driver.get('https://www.jd.com')
    input_tag=driver.find_element(By.ID,'key')
    input_tag.send_keys(good_name)
    input_tag.send_keys(Keys.ENTER)
    time.sleep(2)
    getGood(driver)